<template>
  <view class="container">
    <view class="content-wrapper">
      <!-- 左侧自定义分段器 -->
      <view class="left-segmented-control">
        <view 
          class="segmented-item" 
          :class="{active: currentTab === index}" 
          v-for="(category, index) in categories" 
          :key="index" 
          @click="switchTab(index)">
          {{category.name}}
        </view>
      </view>
      
      <!-- 右侧内容展示区 -->
      <view class="right-content-container">
        <view v-if="isLoading" class="loading-tip">加载中...</view>
        <view v-else-if="errorMsg" class="error-tip">{{errorMsg}}</view>
        <view v-else class="product-list">
          <view v-if="currentProducts.length === 0" class="empty-tip">暂无此类商品</view>
          <view class="product-item" v-else v-for="item in currentProducts" :key="item.id">
            <image class="product-image" :src="item.imageUrl || 'https://picsum.photos/200/300'" mode="aspectFill"></image>
            <view class="product-info">
              <view class="product-name">{{item.name || '商品名称'}}</view>
              <view class="product-desc">{{item.introduce || '商品介绍'}}</view>
              <view class="product-price">¥{{item.price || '0.00'}}</view>
              <!-- 购物车数量控制器 -->
              <view class="cart-controller" v-if="cartItems[item.id] && cartItems[item.id].count > 0">
                <view class="decrease-btn" @click="decreaseCount(item.id)">-</view>
                <view class="count">{{cartItems[item.id].count}}</view>
                <view class="increase-btn" @click="increaseCount(item.id)">+</view>
              </view>
              <!-- 加入购物车按钮 -->
              <view class="add-cart-btn" v-else @click="addToCart(item.id)">
                <text class="iconfont icon-gouwuche"></text>
                <text>加入购物车</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 底部购物导航栏 -->
    <view class="shopping-bar">
      <view class="cart-icon">
	  <image class="iconfont" src="../../static/购物车.png" mode="widthFix"></image>
        <view class="cart-count" v-if="cartCount > 0">{{cartCount}}</view>
      </view>
      <view class="total-price">
        <text>总计: ¥<text class="price-number">{{totalPrice.toFixed(2)}}</text></text>
      </view>
      <view class="buy-button" @click="checkout">结算</view>
    </view>
  </view>
</template>

<script>
import { listShop, getShop, delShop, addShop, updateShop } from "@/pages/store/store.js"

export default {
  name: "Shop",
  data() {
    return {
      currentTab: 0,
      cartItems: {}, // 存储购物车中每个商品的数量
      cartCount: 0,
      totalPrice: 0,
      categories: [
        { id: 1, name: '健身器材' },
        { id: 2, name: '健康代餐' },
        { id: 3, name: '养生茶饮' },
        { id: 4, name: '功能饮料' }
      ],
      products: [],
      isLoading: false,
      errorMsg: '',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        price: null,
        stock: null,
        introduce: null,
        categoryId: null,
        createUser: null,
        updateUser: null,
        isSole: null,
        discount: null,
        solePrice: null
      },
      form: {},
      // 表单校验
      rules: {
        categoryId: [
          { required: true, message: "商品种类表的id不能为空", trigger: "blur" }
        ],
        createUser: [
          { required: true, message: "创建管理员不能为空", trigger: "blur" }
        ],
        updateUser: [
          { required: true, message: "修改管理员不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "修改时间不能为空", trigger: "blur" }
        ],
      }
    }
  },
  computed: {
    currentProducts() {
      return this.products.filter(product => 
        product.categoryId === this.categories[this.currentTab].id
      );
    }
  },
  onLoad() {
    this.getList();
    // 从本地存储加载购物车数据
    this.loadCart();
  },
  methods: {
    /** 查询商品信息列表 */
    getList() {
      this.isLoading = true;
      this.errorMsg = '';
      console.log('开始加载商品数据...');
      
      listShop(this.queryParams).then(response => {
        console.log('API返回的原始数据:', response);
        
        if (!response) {
          this.errorMsg = '获取商品数据失败: 无响应数据';
          console.error('商品数据请求失败:', response);
          return;
        }
        
        // 根据实际接口返回格式调整
        if (response.data && Array.isArray(response.data)) {
          this.products = response.data;
        } else if (response.rows && Array.isArray(response.rows)) {
          this.products = response.rows;
        } else if (response.rows && response.rows.data && Array.isArray(response.rows.data)) {
          this.products = response.rows.data;
        } else {
          this.errorMsg = '获取商品数据失败: 数据格式异常';
          console.error('商品数据格式异常:', response);
        }
        
        console.log('加载完成，当前商品数量:', this.products.length);
        this.isLoading = false;
      }).catch(error => {
        this.errorMsg = '网络请求错误: ' + error.message;
        console.error('商品数据请求错误:', error);
        this.isLoading = false;
      });
    },
    
    // 从本地存储加载购物车
    loadCart() {
      try {
        const cart = uni.getStorageSync('shoppingCart');
        if (cart) {
          this.cartItems = cart;
          this.updateCartStats();
        }
      } catch (e) {
        console.error('加载购物车失败:', e);
      }
    },
    
    // 保存购物车到本地存储
    saveCart() {
      try {
        uni.setStorageSync('shoppingCart', this.cartItems);
      } catch (e) {
        console.error('保存购物车失败:', e);
      }
    },
     switchTab(index) {
          this.currentTab = index;
        },
    // 更新购物车统计信息
    updateCartStats() {
      let count = 0;
      let price = 0;
      
      Object.values(this.cartItems).forEach(item => {
        count += item.count;
        price += item.count * item.price;
      });
      
      this.cartCount = count;
      this.totalPrice = price;
    },
    
    // 增加商品数量
    increaseCount(productId) {
      const product = this.products.find(item => item.id === productId);
      if (!product) return;
      
      if (!this.cartItems[productId]) {
        this.cartItems[productId] = {
          id: productId,
          name: product.name,
          price: product.price,
          count: 0
        };
      }
      
      this.cartItems[productId].count += 1;
      this.updateCartStats();
      this.saveCart();
    },
    
    // 减少商品数量
    decreaseCount(productId) {
      if (!this.cartItems[productId] || this.cartItems[productId].count <= 0) return;
      
      this.cartItems[productId].count -= 1;
      
      // 如果数量为0，移除该商品
      if (this.cartItems[productId].count === 0) {
        delete this.cartItems[productId];
      }
      
      this.updateCartStats();
      this.saveCart();
    },
    
    // 添加到购物车
    addToCart(productId) {
      const product = this.products.find(item => item.id === productId);
      if (!product) {
        console.error('未找到商品，ID:', productId);
        uni.showToast({
          title: '商品不存在',
          icon: 'none'
        });
        return;
      }
      
      if (!this.cartItems[productId]) {
        this.cartItems[productId] = {
          id: productId,
          name: product.name,
          price: product.price,
          count: 0
        };
      }
      
      this.cartItems[productId].count += 1;
      this.updateCartStats();
      this.saveCart();
      
      uni.showToast({
        title: '已添加到购物车',
        icon: 'success'
      });
    },
    
    // 结算
    checkout() {
      if (this.cartCount === 0) {
        uni.showToast({
          title: '购物车为空',
          icon: 'none'
        });
        return;
      }
      
      // 跳转到结算页面
      uni.navigateTo({
        url: '/pages/checkout/checkout'
      });
    }
  }
}
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.content-wrapper {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.left-segmented-control {
  width: 200rpx;
  background-color: #f8f8f8;
  overflow-y: auto;
}

.segmented-item {
  height: 100rpx;
  line-height: 100rpx;
  text-align: center;
  font-size: 28rpx;
  color: #333;
  border-bottom: 1rpx solid #eee;
  background-color: #66CDAA;
}

.segmented-item.active {
  color: #fff;
  font-weight: bold;
  background-color: #3CB371;
}

.right-content-container {
  flex: 1;
  overflow-y: auto;
  padding: 20rpx;
  background-color: #fff;
}

.loading-tip, .error-tip, .empty-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  font-size: 28rpx;
  color: #666;
}

.product-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.product-item {
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
}

.product-image {
  width: 100%;
  height: 300rpx;
}

.product-info {
  padding: 16rpx;
}

.product-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-desc {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 12rpx;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-price {
  font-size: 30rpx;
  color: #ff5500;
  font-weight: bold;
  margin-bottom: 12rpx;
}

/* 购物车数量控制器 */
.cart-controller {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60rpx;
}

.decrease-btn, .increase-btn {
  width: 60rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  background-color: #ff5500;
  color: white;
  font-size: 32rpx;
  border-radius: 50%;
}

.count {
  width: 80rpx;
  text-align: center;
  font-size: 28rpx;
  color: #333;
}

/* 加入购物车按钮 */
.add-cart-btn {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60rpx;
  background-color: #ff5500;
  color: white;
  border-radius: 30rpx;
  font-size: 24rpx;
  padding: 0 16rpx;
}

.add-cart-btn .iconfont {
  margin-right: 8rpx;
  width: auto;
  height: 8rpx;
}

.shopping-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100rpx;
  padding: 0 30rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
}

.cart-icon {
  position: relative;
  width: 60rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  font-size: 40rpx;
  color: #ff5500;
}

.cart-count {
  position: absolute;
  top: -6rpx;
  right: -6rpx;
  width: 32rpx;
  height: 32rpx;
  line-height: 32rpx;
  text-align: center;
  background-color: #ff5500;
  color: #fff;
  font-size: 20rpx;
  border-radius: 50%;
}

.total-price {
  font-size: 28rpx;
  color: #333;
}

.price-number {
  color: #ff5500;
  font-weight: bold;
}

.buy-button {
  width: 200rpx;
  height: 70rpx;
  line-height: 70rpx;
  text-align: center;
  background-color: #66CDAA;
  color: #fff;
  font-size: 28rpx;
  border-radius: 35rpx;
}
</style>    